<template>
    <div class="mainten-time-dimension-wrap">
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item v-if="$store.state.userinfo.isMuilUnitUser === 1">
                    <el-select filterable @change="search" v-model="searchForm.orgId" placeholder="请选择业主单位">
                        <el-option
                        v-for="item in orgOptions"
                        :key="item.organizationId"
                        :label="item.shortName"
                        :value="item.organizationId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-row class="time-choose-wrap">
                        <el-col :span="6">
                            <el-select filterable @change="dateTypeChange" v-model="searchForm.dateType">
                                <el-option label="月" value="month"></el-option>
                                <el-option label="年" value="year"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="18">
                            <el-date-picker
                                @change="search"
                                v-model="searchForm.time"
                                :type="searchForm.dateType"
                                :format="dateFormat"
                                :value-format="dateFormat"
                                :placeholder="timePlaceholder">
                            </el-date-picker>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-select filterable @change="search" v-model="searchForm.maintainType" placeholder="请选择维保类型">
                        <el-option
                            v-for="item in maintenanceTypeOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select filterable @change="search" v-model="searchForm.workPeriod" placeholder="请选择维保周期">
                        <el-option
                            v-for="item in maintenanceCycleOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row type="flex" justify="center" class="maintenTimeDimension-echarts-header">
            <el-col :span="4">
                <p>任务总数：{{ (resultData.totalFinishCount || 0)  + (resultData.totalUnfinishCount || 0)}}</p>
            </el-col>
            <el-col :span="4">
                <p>完成任务数：{{ resultData.totalFinishCount || 0 }}</p>
            </el-col>
            <el-col :span="4">
                <p>未完成任务数：{{ resultData.totalUnfinishCount || 0 }}</p>
            </el-col>
            <el-col :span="4">
                <p>任务完成率：{{ completionRate }}</p>
            </el-col>
        </el-row>
        <!-- 分析结果图 -->
        <div id="maintenTimeDimensionEcharts" class="maintenTimeDimensionEcharts"></div>
    </div>
</template>
<script>
import util from '@/utils/util'
import { getOrgList } from '@/api/org'
import { getMaintainAnalysisByTime } from '@/api/maintence'

export default {
    name: 'TimeDimension',
    data() {
        return {
            // 维保类型
            maintenanceTypeOptions: [
                {
                    id: 0,
                    name: '全部维保类型' 
                },{
                    id: 1,
                    name: '维保巡查' 
                }, {
                    id: 2,
                    name: '保养' 
                }, {
                    id: 3,
                    name: '单点测试'  
                }, {
                    id: 4,
                    name: '联动测试' 
                }
            ],
            // 维保周期
            maintenanceCycleOptions: [
                {
                    id: 0,
                    name: '全部维保周期'
                }, {
                    id: 1,
                    name: '月'
                }, {
                    id: 2,
                    name: '季'
                }, {
                    id: 3,
                    name: '半年'
                }, {
                    id: 4,
                    name: '年'
                },
            ],
            orgOptions: [],
            dateFormat: 'yyyy-MM',
            timePlaceholder: '请选择月度',
            searchForm: {
                orgId: '',
                dateType: 'month', // 时间查询的类型，默认月  'month'-月   'year'-年
                time: util.ilinkTimeformat.format(new Date(), 'yyyy-MM'), 
                maintainType: 0, // 维保类型
                workPeriod: 0 // 维护周期
            },
            resultData: {
                totalFinishCount: 0,
                totalUnfinishCount: 0
            },
            completionRate: '' // 任务完成率
        }
    },
    created() {
        let that = this
        if(that.$store.state.userinfo.isMuilUnitUser === 1) {
            // 获取业主单位信息
            getOrgList({
                queryType: 0
            }).then(res => {
                if(res.status = 200) {
                    that.orgOptions = res.data
                    that.searchForm.orgId = that.orgOptions[0].organizationId

                    that.search()
                }
            })
        } else {
            that.searchForm.orgId = that.$store.state.userinfo.org.id
            this.search()
        }
    },
    methods: {
        dateTypeChange(val) {
            if(val) {
                this.searchForm.dateType = val
                this.timePlaceholder = val == 'month' ? '请选择月度' : '请选择年度'
                this.dateFormat = val == 'month' ? 'yyyy-MM' : 'yyyy'
                this.searchForm.time = val == 'month' ? util.ilinkTimeformat.format(new Date(), 'yyyy-MM') : util.ilinkTimeformat.format(new Date(), 'yyyy')
                this.getMaintenTimeData()
            }
        },
        search() {
            this.getMaintenTimeData()
        },
        getMaintenTimeData() {
            getMaintainAnalysisByTime({
                orgId: this.searchForm.orgId,
                dateType: this.searchForm.dateType == 'month' ? 1 : 2,
                date: this.searchForm.time,
                period: this.searchForm.workPeriod,
                workType: this.searchForm.maintainType
            }).then(res => {
                if(res.status === 200) {
                    this.resultData = res.data
                    this.completionRate = this.calcCompletionRate(res.data.totalFinishCount, res.data.totalFinishCount+res.data.totalUnfinishCount)
                    this.renderAnalusisEcharts(res.data.details)
                }
            })
        },
        // 渲染柱状图
        renderAnalusisEcharts(res) {
            let that = this
            let data = res
            let xAxisData = []
            let doneData = []
            let undoneData = []
            let completionRateData = []

            for(let i=0, len=data.length; i < len; i++) {
                xAxisData.push(data[i].fireSystemName)
                doneData.push(data[i].finishCount)
                undoneData.push(data[i].unfinishCount)
                completionRateData.push(that.calcCompletionRate(data[i].finishCount, data[i].finishCount + data[i].unfinishCount))
            }
            
            let option_echart = {
                tooltip: {
                    trigger: "axis",
                    formatter: function(params) {
                        let str = `${params[0].axisValueLabel}<br/>完成率：${completionRateData[params[0].dataIndex]}<br/>${params[0].marker}未完成任务：${params[0].value}<br/>${params[1].marker}已完成任务：${params[1].value}`
                        return str
                    }
                },
                color: ["#FFB32D", "#47CFAD"],
                legend: {
                    top: "0",
                    data: ["未完成", "已完成"],
                    itemGap: 10,
                    itemWidth: 15,
                    itemHeight: 12
                },
                grid: {
		            bottom: 100,
                },
                xAxis: [{
                    type: "category",
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 30
                    },
                    data: xAxisData
                }],
                yAxis: [{
                    type: "value",
                    name: "任务数",
                    minInterval: 1
                }],
                series: [{
                    data: undoneData,
                    name: "未完成",
                    stack: "one",
                    type: "bar",
                }, {
                    data: doneData,
                    name: "已完成",
                    stack: "one",
                    type: "bar",
                    label: {
                        show: true,
                        position: 'top',
                        color: '#4CA4FE',
                        fontSize: 16,
                        formatter: function(params) {
                            return completionRateData[params.dataIndex]
                        }
                    },
                }]
            }

            that.$echarts.init(document.getElementById('maintenTimeDimensionEcharts')).setOption(option_echart, true); 
        },
        // 计算完成率
        calcCompletionRate(num, total) {
            let result = util.accDiv(num, total)

            result = Math.floor(result * 10000) / 100 
            return (result || 0) + '%'
        }
    },
}
</script>
<style lang="scss" scoped>
.mainten-time-dimension-wrap {
    .time-choose-wrap {
        width: 350px;
    }
    .maintenTimeDimensionEcharts {
        margin-top: 20px;
        width: 100%;
        height: 550px;
    }
}
</style>